package kz.edu.sdu.atm.ui.client;

import kz.edu.sdu.atm.client.Client;
import kz.edu.sdu.atm.models.UserDTO;

import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QHBoxLayout;
import com.trolltech.qt.gui.QLabel;
import com.trolltech.qt.gui.QLineEdit;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QVBoxLayout;
import com.trolltech.qt.gui.QWidget;
import com.trolltech.qt.gui.QLineEdit.EchoMode;

public class LoginForm extends QMyWidget {

	QLineEdit login;
	QLineEdit password;

	QPushButton ok;
	QPushButton quit;

	MainMenu menu;
	UserDTO user;

    public static void main(String[] args) {
        QApplication.initialize(args);
		String host = "localhost";
		int port = 12345;
		if (args.length == 2) {
			host = args[0];
			port = Integer.parseInt(args[1]);
		}
		Client client = new Client(host, port);
		LoginForm testLoginForm = new LoginForm(null, client);
        testLoginForm.show();

        QApplication.exec();
    }

	public LoginForm(QWidget parent, Client client) {
		super(parent, client);
    }

	@Override
	void connectAll() {
		quit.clicked.connect(QApplication.instance(), "quit()");
		ok.clicked.connect(this, "auth()");
	}

	public MainMenu getMainMenu() {
		if (menu == null) {
			menu = new MainMenu(this, client, user);
		}
		return menu;
	}

	public void auth() {
		user = new UserDTO();
		user.setUsername(login.text());
		user.setPassword(password.text());
		if (client.auth(user.getUsername(), user.getPassword())) {
			hide();
			getMainMenu().show();
		} else {
			showMessage("Invalid Login!");
		}
	}


	@Override
	void init() {
		login = new QLineEdit();
		password = new QLineEdit();
		ok = new QPushButton("Login");
		quit = new QPushButton("Quit");
		password.setEchoMode(EchoMode.PasswordEchoOnEdit);
		setFixedSize(400, 200);
		layout = new QVBoxLayout();
		layout.addWidget(new QLabel("Login:"));
		layout.addWidget(login);
		layout.addWidget(new QLabel("Password:"));
		layout.addWidget(password);

		QHBoxLayout buttonLayout = new QHBoxLayout();
		buttonLayout.addWidget(ok);
		buttonLayout.addWidget(quit);
		layout.addItem(buttonLayout);

		setLayout(layout);
	}

}
